@file:Suppress("unused")

package com.hjh.tool.extension

import android.content.Context
import android.view.View
import android.view.WindowManager
import android.widget.PopupWindow

/**
 * @author： hjh
 * @createDate： 2025/6/10 14:51
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */

/**
 * 计算出PopUpWindow显示的高度
 * @param context Context
 * @return PopUpWindow的高度
 */
fun PopupWindow?.calculatePopWindowHeight(context: Context): Int {
    if (this == null) return 0
    val screenWidth = context.resources.displayMetrics.widthPixels
    // 若popupWindow高度已被定义,可直接返回
    if (this.height > 0) {
        return this.height
    }
    val thisWidth = this.width
    // 根据this的宽度来选择PopUpWindow的测量模式
    val measureWidthParams = when {
        thisWidth > 0 -> {
            View.MeasureSpec.makeMeasureSpec(thisWidth, View.MeasureSpec.EXACTLY)
        }

        thisWidth == WindowManager.LayoutParams.MATCH_PARENT -> {
            View.MeasureSpec.makeMeasureSpec(screenWidth, View.MeasureSpec.EXACTLY)
        }

        thisWidth == WindowManager.LayoutParams.WRAP_CONTENT -> {
            // 若this的宽度为WRAP_CONTENT，测量会存在偏差。因此需要设置PopUpWindow的宽度为屏幕宽度的一半，测试模式为精准测量
            this.width = screenWidth / 2
            View.MeasureSpec.makeMeasureSpec(screenWidth / 2, View.MeasureSpec.EXACTLY)
        }

        else -> 0
    }
    this.contentView.measure(
        measureWidthParams,
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
    )
    return this.contentView.measuredHeight
}

/**
 * 显示PopUpWindow在参考布局之上
 * @param context Context
 * @param anchorView 参考布局
 */
fun PopupWindow.showAsAbove(context: Context, anchorView: View?) {
    val popupWindowHeight = this.calculatePopWindowHeight(context)
    val anchorViewHeight = anchorView?.calculateViewHeight() ?: 0
    // 实际需要偏移的高度为参考view的高度加上PopUpWindow的高度
    val yOffset = -(popupWindowHeight + anchorViewHeight)
    this.showAsDropDown(anchorView, 0, yOffset)
}